#include "core/enhanced_chat_system.h"
#include <iostream>
#include <thread>
#include <chrono>

void printSeparator(const std::string& title) {
    std::cout << "\n" << std::string(60, '=') << std::endl;
    std::cout << "  " << title << std::endl;
    std::cout << std::string(60, '=') << std::endl;
}

void demonstratePrivateChatInitiation() {
    printSeparator("单聊发起方式演示");
    
    EnhancedChatSystem chatSystem;
    
    // 1. 用户上线
    std::cout << "🔗 步骤1: 用户登录系统" << std::endl;
    chatSystem.addUser("Alice", 1001, "192.168.1.101");
    chatSystem.addUser("Bob", 1002, "192.168.1.102");
    chatSystem.addUser("Charlie", 1003, "192.168.1.103");
    std::cout << "  ✅ Alice, Bob, Charlie 已上线" << std::endl;
    
    // 2. 方式一：直接发送消息自动创建会话
    std::cout << "\n💬 方式一: 直接发送消息 (自动创建会话)" << std::endl;
    std::cout << "  Alice 想对 Bob 说话..." << std::endl;
    
    bool success = chatSystem.sendPrivateMessage("Alice", "Bob", "Hi Bob, 你好！");
    if (success) {
        std::cout << "  ✅ 消息发送成功，会话自动创建" << std::endl;
        
        // 查看创建的会话
        auto chat = chatSystem.getPrivateChat("Alice", "Bob");
        if (chat) {
            std::cout << "  📱 会话ID: " << chat->chatId << std::endl;
            std::cout << "  👥 参与者: " << chat->user1 << ", " << chat->user2 << std::endl;
            std::cout << "  📝 消息数: " << chat->messages.size() << " 条" << std::endl;
        }
    }
    
    // 3. 方式二：先创建会话再发送消息
    std::cout << "\n💬 方式二: 先创建会话后发送消息" << std::endl;
    std::cout << "  Alice 想和 Charlie 建立聊天..." << std::endl;
    
    std::string chatId = chatSystem.startPrivateChat("Alice", "Charlie");
    std::cout << "  ✅ 会话创建成功: " << chatId << std::endl;
    
    // 发送消息
    chatSystem.sendPrivateMessage("Alice", "Charlie", "Hello Charlie!");
    chatSystem.sendPrivateMessage("Charlie", "Alice", "Hi Alice, nice to meet you!");
    
    std::cout << "  💬 Alice -> Charlie: Hello Charlie!" << std::endl;
    std::cout << "  💬 Charlie -> Alice: Hi Alice, nice to meet you!" << std::endl;
    
    // 4. 查看会话历史
    std::cout << "\n📋 会话历史查看" << std::endl;
    auto aliceCharlieChat = chatSystem.getPrivateChat("Alice", "Charlie");
    if (aliceCharlieChat) {
        std::cout << "  会话: " << aliceCharlieChat->chatId << std::endl;
        std::cout << "  消息历史:" << std::endl;
        for (const auto& msg : aliceCharlieChat->messages) {
            std::cout << "    [" << msg.fromUser << " -> " << msg.toUser << "] " 
                      << msg.content << std::endl;
        }
    }
    
    // 5. 查看用户的所有私聊
    std::cout << "\n👤 Alice 的私聊列表" << std::endl;
    auto alice = chatSystem.getUser("Alice");
    if (alice) {
        std::cout << "  Alice 参与的私聊数量: " << alice->privateChats.size() << std::endl;
        for (const std::string& chatId : alice->privateChats) {
            std::cout << "    - " << chatId << std::endl;
        }
    }
}

void demonstrateClientSideUsage() {
    printSeparator("客户端使用方式");
    
    std::cout << "📱 客户端发起单聊的典型流程:" << std::endl;
    std::cout << "\n1. 用户选择聊天对象" << std::endl;
    std::cout << "   - 从联系人列表选择" << std::endl;
    std::cout << "   - 搜索用户名" << std::endl;
    std::cout << "   - 扫描二维码添加" << std::endl;
    
    std::cout << "\n2. 客户端发送消息请求" << std::endl;
    std::cout << "   消息格式示例:" << std::endl;
    std::cout << "   ```" << std::endl;
    std::cout << "   type: MSG_PRIVATE_CHAT" << std::endl;
    std::cout << "   fromUser: Alice" << std::endl;
    std::cout << "   toUser: Bob" << std::endl;
    std::cout << "   content: Hello Bob!" << std::endl;
    std::cout << "   chatType: CHAT_PRIVATE" << std::endl;
    std::cout << "   ```" << std::endl;
    
    std::cout << "\n3. 服务器处理流程" << std::endl;
    std::cout << "   ✅ 验证用户身份" << std::endl;
    std::cout << "   ✅ 检查目标用户是否存在" << std::endl;
    std::cout << "   ✅ 创建或获取私聊会话" << std::endl;
    std::cout << "   ✅ 保存消息到会话历史" << std::endl;
    std::cout << "   ✅ 转发消息给目标用户" << std::endl;
    
    std::cout << "\n4. 目标用户接收消息" << std::endl;
    std::cout << "   📱 客户端收到消息通知" << std::endl;
    std::cout << "   🔔 显示消息提醒" << std::endl;
    std::cout << "   💬 更新聊天界面" << std::endl;
}

void demonstrateMessageProtocol() {
    printSeparator("消息协议详解");
    
    std::cout << "📡 单聊消息协议格式:" << std::endl;
    std::cout << "\n发送消息 (客户端 -> 服务器):" << std::endl;
    std::cout << "```" << std::endl;
    std::cout << "3|msg_id_12345|Alice|Bob||Hello Bob!|1703123456|1" << std::endl;
    std::cout << "```" << std::endl;
    std::cout << "字段解释:" << std::endl;
    std::cout << "  3 = MSG_PRIVATE_CHAT" << std::endl;
    std::cout << "  msg_id_12345 = 消息ID" << std::endl;
    std::cout << "  Alice = 发送者" << std::endl;
    std::cout << "  Bob = 接收者" << std::endl;
    std::cout << "  (空) = 群组ID (私聊为空)" << std::endl;
    std::cout << "  Hello Bob! = 消息内容" << std::endl;
    std::cout << "  1703123456 = 时间戳" << std::endl;
    std::cout << "  1 = CHAT_PRIVATE" << std::endl;
    
    std::cout << "\n接收消息 (服务器 -> 客户端):" << std::endl;
    std::cout << "```" << std::endl;
    std::cout << "3|msg_id_12345|Alice|Bob||Hello Bob!|1703123456|1" << std::endl;
    std::cout << "```" << std::endl;
    std::cout << "客户端解析后显示:" << std::endl;
    std::cout << "  [Alice] Hello Bob!  (12:34)" << std::endl;
}

void demonstrateAdvancedFeatures() {
    printSeparator("高级功能演示");
    
    EnhancedChatSystem chatSystem;
    chatSystem.addUser("Alice", 1001, "192.168.1.101");
    chatSystem.addUser("Bob", 1002, "192.168.1.102");
    
    std::cout << "🚀 高级单聊功能:" << std::endl;
    
    // 1. 会话ID生成规则
    std::cout << "\n1. 会话ID生成规则 (字典序排序)" << std::endl;
    std::string chatId1 = chatSystem.startPrivateChat("Alice", "Bob");
    std::string chatId2 = chatSystem.startPrivateChat("Bob", "Alice");
    std::cout << "  Alice->Bob 会话ID: " << chatId1 << std::endl;
    std::cout << "  Bob->Alice 会话ID: " << chatId2 << std::endl;
    std::cout << "  ✅ 两个ID相同，确保会话唯一性" << std::endl;
    
    // 2. 消息历史持久化
    std::cout << "\n2. 消息历史持久化" << std::endl;
    chatSystem.sendPrivateMessage("Alice", "Bob", "第一条消息");
    chatSystem.sendPrivateMessage("Bob", "Alice", "第二条消息");
    chatSystem.sendPrivateMessage("Alice", "Bob", "第三条消息");
    
    auto chat = chatSystem.getPrivateChat("Alice", "Bob");
    if (chat) {
        std::cout << "  📝 会话中共有 " << chat->messages.size() << " 条消息" << std::endl;
        std::cout << "  🕐 最后活跃时间: " << chat->lastActiveTime << std::endl;
    }
    
    // 3. 用户私聊列表管理
    std::cout << "\n3. 用户私聊列表自动管理" << std::endl;
    chatSystem.addUser("Charlie", 1003, "192.168.1.103");
    chatSystem.startPrivateChat("Alice", "Charlie");
    
    auto alice = chatSystem.getUser("Alice");
    if (alice) {
        std::cout << "  👤 Alice 的私聊列表:" << std::endl;
        for (const std::string& chatId : alice->privateChats) {
            std::cout << "    - " << chatId << std::endl;
        }
    }
    
    // 4. 线程安全演示
    std::cout << "\n4. 并发安全性" << std::endl;
    std::cout << "  🔒 所有操作都有互斥锁保护" << std::endl;
    std::cout << "  🔒 支持多线程并发访问" << std::endl;
    std::cout << "  🔒 避免竞态条件和数据竞争" << std::endl;
}

void demonstrateErrorHandling() {
    printSeparator("错误处理演示");
    
    EnhancedChatSystem chatSystem;
    chatSystem.addUser("Alice", 1001, "192.168.1.101");
    
    std::cout << "❌ 常见错误情况处理:" << std::endl;
    
    // 1. 发送给不存在的用户
    std::cout << "\n1. 发送给不存在的用户" << std::endl;
    bool result = chatSystem.sendPrivateMessage("Alice", "NonExistentUser", "Hello");
    std::cout << "  结果: " << (result ? "成功" : "失败") << std::endl;
    std::cout << "  说明: 消息会被发送，但目标用户收不到" << std::endl;
    
    // 2. 不存在的用户发送消息
    std::cout << "\n2. 不存在的用户发送消息" << std::endl;
    bool result2 = chatSystem.sendPrivateMessage("NonExistentUser", "Alice", "Hello");
    std::cout << "  结果: " << (result2 ? "成功" : "失败") << std::endl;
    std::cout << "  说明: 会话会被创建，但发送者不在系统中" << std::endl;
    
    // 3. 查看不存在的会话
    std::cout << "\n3. 查看不存在的会话" << std::endl;
    auto chat = chatSystem.getPrivateChat("Alice", "NonExistentUser");
    std::cout << "  结果: " << (chat ? "找到会话" : "会话不存在") << std::endl;
    
    std::cout << "\n💡 建议的错误处理策略:" << std::endl;
    std::cout << "  ✅ 发送前验证用户是否在线" << std::endl;
    std::cout << "  ✅ 提供消息发送状态反馈" << std::endl;
    std::cout << "  ✅ 离线消息存储和推送" << std::endl;
    std::cout << "  ✅ 网络异常重试机制" << std::endl;
}

int main() {
    std::cout << "🚀 单聊发起完整指南" << std::endl;
    
    // 基本发起方式
    demonstratePrivateChatInitiation();
    
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    
    // 客户端使用方式
    demonstrateClientSideUsage();
    
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    
    // 消息协议
    demonstrateMessageProtocol();
    
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    
    // 高级功能
    demonstrateAdvancedFeatures();
    
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    
    // 错误处理
    demonstrateErrorHandling();
    
    printSeparator("总结");
    std::cout << "📝 单聊发起要点:" << std::endl;
    std::cout << "1. 🎯 两种方式: 直接发消息 或 先创建会话" << std::endl;
    std::cout << "2. 🔄 会话自动创建和管理" << std::endl;
    std::cout << "3. 📱 会话ID按字典序生成，确保唯一性" << std::endl;
    std::cout << "4. 💾 消息历史自动保存" << std::endl;
    std::cout << "5. 🔒 线程安全的并发处理" << std::endl;
    std::cout << "6. 📡 标准化的消息协议" << std::endl;
    
    return 0;
} 